#include "./proto.h"
#include <stdio.h>

uint8_t proto_xor_sum(const uint8_t *buf, uint16_t len) {
    uint8_t s = 0;
    for (uint16_t i = 0; i < len; i ++) {
        s ^= buf[i];
    }
    return s;
}

static uint8_t logSeq = 0;

// e1 1e len type seq cmd log_len ... sum ef
uint16_t proto_make_printf(uint8_t *buf, const char *fmt, va_list ap) {
    buf[0] = HEAD0;
    buf[1] = HEAD1;
   // buf[2] = 0;
    buf[3] = TYPE_NOTIFY;
    buf[4] = logSeq;
    buf[5] = STATUS_LOG;

    int n = vsprintf((char *) buf + 7, fmt, ap);

    buf[2] = n + 6;
    buf[6] = n;

    uint8_t sum = proto_xor_sum(buf + 3, 4 + n);
    buf[7 + n] = sum;
    buf[8 + n] = END;
    buf[2] = 9 + n;

    logSeq ++;

    return 9 + n;
}

uint16_t proto_make_simple_res(uint8_t *buf, uint8_t seq, uint8_t cmd, uint8_t ec) {
    buf[0] = HEAD0;
    buf[1] = HEAD1;
    buf[2] = 9;
    buf[3] = TYPE_SIMPLE_RES;
    buf[4] = seq;
    buf[5] = cmd;
    buf[6] = ec;
    buf[7] = proto_xor_sum(buf + 3, 4);
    buf[8] = END;
    return 9;
}

